package com.ios.service.impl;

import com.ios.dao.FMMapper;
import com.ios.dto.FMExecution;
import com.ios.entity.FM;
import com.ios.enums.FMStateEnum;
import com.ios.service.IFMService;
import com.ios.util.FMUtil;
import com.ios.util.ImageUtil;
import com.ios.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
public class FMServiceImpl implements IFMService{
    @Autowired
    private FMMapper fmMapper;

    @Override
    public FMExecution AddFM(FM fm, InputStream FMInputStream, String fileName){
        if (fm ==null || fileName==null||FMInputStream==null){
            return new FMExecution(FMStateEnum.PARAM);
        }else {
            try{
                fm.setCreateTime(new Date());
                fm.setUpdateTime(new Date());
                try{
                    fm.setContent(addFMFile(fm,FMInputStream,fileName));
                }catch (Exception e){
                    return new FMExecution(FMStateEnum.FAIL_ADD);
                }
            }catch (Exception e){
                return new FMExecution(FMStateEnum.FAIL_ADD);
            }
        }
        fmMapper.insert(fm);
        return new FMExecution(FMStateEnum.SUCCESS_ADD,fm);
    }

    @Override
    public FMExecution ShowList() {
        try{
            List<FM> fmList = fmMapper.selectAll();
            return new FMExecution(FMStateEnum.SUCCESS_SHOW,fmList);
        }catch (Exception e){
            return new FMExecution(FMStateEnum.FAIL_SHOW);
        }
    }

    /*增加存储fm文件*/
    private String addFMFile(FM fm,InputStream FMInputStream,String fileName){
        /*获取头像图片目录的相对路径*/
        String dest = PathUtil.getFMPath();
        String fmAddr = FMUtil.ManageFM(FMInputStream,fileName,dest);
        return fmAddr;
    }
}
